package view;

import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;


/**
 * Class is responsible for logger table.
 * Table is not editable, with specified header.
 * Resize of table is happened when received data take more than current lines number. 
 */
public abstract class AbstractLoggerTable extends JTable
{
	/**
	 * C'tor - create table with defined parameters 
	 * @param width  - number of the table rows
	 * @param length - number of the table columns
	 */
	public AbstractLoggerTable(int width, int length)
	{
		super(width, length);
	}

	/**
	 * Get the data from UI.
	 * @return the logger data from server
	 */
	protected abstract Object[] getLoggerData();
	
	/**
	 * Get the table name.
	 * @return the logger table name
	 */
	protected abstract String getTableName();
	
	/** 
	 * @return the names of the table columns
	 */
	public abstract String[] getColumnNames();
	
	/**
	 * Fill the table with logger data.
	 * @param objectData - the logger data to put to the table
	 */
	protected abstract void fillTable(Object[] loggerData);

	/**
	 * Cancel cell editing for user.
	 * @param row	 - the cell row
	 * @param column - the cell column
	 */
	public boolean isCellEditable(int row, int column) 
	{
		return false;
	}
	
	/**
	 * Create table header.
	 * @return the table header
	 */
	public JTableHeader getLoggerTableHeader()
	{
		String[] columnNames = getColumnNames();
		TableColumn column = null;
		for (int i = 0; i < columnNames.length; i++)
		{
		    column = getColumnModel().getColumn(i);
		    column.setHeaderValue(columnNames[i]);
		}
		
		return getTableHeader();	
	}
	
	/**
	 * Update the table for the logger data.
	 */
	public void buildTable()
	{
		Object[] loggerData = getLoggerData();

		/* Check if data array is valid */
		if(loggerData != null)
		{
			/* Add new rows if it's needed */
			int rowsCount = Math.max(getModel().getRowCount(),Settings.DEFAULT_LOGGER_WINDOW_DEPTH);
			int diff = loggerData.length - rowsCount;
			
			/* Clear the previous data */
			((DefaultTableModel)getModel()).setRowCount(0);
			if(diff > 0)
			{
				((DefaultTableModel)getModel()).setRowCount(loggerData.length);
			}
			else
			{
				((DefaultTableModel)getModel()).setRowCount(rowsCount);
			}
			
			/* Fill the table with data */
			fillTable(loggerData);			
		}
		else /*if(loggerData != null)*/
		{
			/* Clear the previous data */			
			((DefaultTableModel)getModel()).setRowCount(0);
			((DefaultTableModel)getModel()).setRowCount(Settings.DEFAULT_LOGGER_WINDOW_DEPTH);
		}
	}
}
